package com.wanpinghui.supplier.widgets;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.netease.nimlib.sdk.media.record.AudioRecorder;
import com.netease.nimlib.sdk.media.record.IAudioRecordCallback;
import com.netease.nimlib.sdk.media.record.RecordType;
import com.wanpinghui.supplier.MApplication;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.AddAddrBookFriendsActivity;
import com.wanpinghui.supplier.addrbook.AddrBookFragment;
import com.wanpinghui.supplier.common.BaseActivity;
import com.yunshl.yunshllibrary.permission.MPermission;
import com.yunshl.yunshllibrary.utils.LogUtils;

import java.io.File;
import java.io.IOException;

import static com.wanpinghui.supplier.addrbook.AddrBookFragment.REQUEST_READ_CONTACTS;

/**
 * Created by xiongning on 17-12-7.
 */

public class AudioRecorderButton extends android.support.v7.widget.AppCompatButton {

    private static final int STATE_NORMAL = 1;// 默认的状态

    private static final int STATE_RECORDING = 2;// 正在录音

    private static final int STATE_WANT_TO_CANCEL = 3;// 希望取消

    private int mCurrentState = STATE_NORMAL; // 当前的状态

    private boolean isRecording = false;// 已经开始录音

    private static final int DISTANCE_Y_CANCEL = 50;

    private DialogManager mDialogManager;

    private float mTime;
    // 是否触发longClick
    private boolean mReady;

    private static final int MSG_AUDIO_PREPARED = 0x110;

    private static final int MSG_VOICE_CHANGED = 0x111;

    private static final int MSG_DIALOG_DIMISS = 0x112;

    public static int maxDuration = 120;

    private AudioRecorder recorder;

    private IAudioRecorderListener mIAudioRecorderListener;

    public interface IAudioRecorderListener {
        void onSendAudio(String audioPath, int sends);
        void onRequestPermission();
    }

    public void registerIAudioRecorder(IAudioRecorderListener mIAudioRecorderListener) {
        this.mIAudioRecorderListener = mIAudioRecorderListener;
    }

    // 定义录音过程回调对象
    private IAudioRecordCallback callback;

    public AudioRecorderButton(Context context) {
        super(context);
        init();
    }

    public AudioRecorderButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AudioRecorderButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    private void init() {

        callback = new IAudioRecordCallback() {
            @Override
            public void onRecordReady() {
                // 初始化完成回调，提供此接口用于在录音前关闭本地音视频播放（可选）
                mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
            }

            @Override
            public void onRecordStart(File audioFile, RecordType recordType) {
                // 开始录音回调
            }

            @Override
            public void onRecordSuccess(File audioFile, long audioLength, RecordType recordType) {
                // 录音结束，成功
                int len = 0;
                try {
                    MediaPlayer mMediaPlayer = new MediaPlayer();
                    mMediaPlayer.setDataSource(audioFile.getAbsolutePath());
                    mMediaPlayer.prepare();
                    len = mMediaPlayer.getDuration();
                    mMediaPlayer.release();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (mIAudioRecorderListener != null)
                    mIAudioRecorderListener.onSendAudio(audioFile.getAbsolutePath(), len);

                mHandler.sendEmptyMessage(MSG_DIALOG_DIMISS);
            }

            @Override
            public void onRecordFail() {
                // 录音结束，出错
            }

            @Override
            public void onRecordCancel() {
                // 录音结束， 用户主动取消录音
            }

            @Override
            public void onRecordReachedMaxTime(int maxTime) {
                // 到达指定的最长录音时间
            }
        };
        // 初始化recorder
        recorder = new AudioRecorder(getContext(), RecordType.AAC, // 录制音频类型（aac/amr)
                maxDuration, // 最长录音时长，到该长度后，会自动停止录音, 默认120s
                callback // 录音过程回调
        );

        mDialogManager = new DialogManager(getContext());

        /*String dir = "/storage/sdcard0/my_weixin";
        //String dir = Environment.getExternalStorageDirectory()+"/my_weixin";

        mAudioManager = AudioManager.getInstance(dir);
        mAudioManager.setOnAudioStateListener(new AudioStateListener() {

            public void wellPrepared() {
                mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
            }
        });*/

        // 由于这个类是button所以在构造方法中添加监听事件
        setOnLongClickListener(new OnLongClickListener() {

            public boolean onLongClick(View v) {
             /*   if(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    if(mIAudioRecorderListener!=null)
                        mIAudioRecorderListener.onRequestPermission();
                }
                else{
                    mReady = true;
                    if (!recorder.startRecord()) {
                        // 开启录音失败。
                    }
                }*/
                mReady = true;
                if (!recorder.startRecord()) {
                    // 开启录音失败。
                }
                return false;

            }
        });
    }

    /*
 * 获取音量大小的线程
 */
    private Runnable mGetVoiceLevelRunnable = new Runnable() {

        public void run() {
            while (isRecording) {
                try {
                    Thread.sleep(100);
                    mTime += 0.1f;
                    mHandler.sendEmptyMessage(MSG_VOICE_CHANGED);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_AUDIO_PREPARED:
                    // 显示對話框在开始录音以后
                    mDialogManager.showRecordingDialog();
                    isRecording = true;
                    // 开启一个线程
                    new Thread(mGetVoiceLevelRunnable).start();
                    break;

                case MSG_VOICE_CHANGED:
                    mDialogManager.updateVoiceLevel(getVoiceLevel(7));
                    break;

                case MSG_DIALOG_DIMISS:
                    mDialogManager.dimissDialog();
                    break;

            }

            super.handleMessage(msg);
        }
    };

    public int getVoiceLevel(int maxlevel) {
        if (recorder.isRecording()) {
            try {
                // mMediaRecorder.getMaxAmplitude() 1~32767

                float maxAmp = recorder.getCurrentRecordMaxAmplitude();
                LogUtils.w("录音振幅======:" + maxAmp);
                LogUtils.w("录音振幅音量======:" + (maxAmp / 7000f));
                int level = (int) ((maxlevel - 1) * (maxAmp / 7000f) + 1);
                LogUtils.w("录音音量:" + level);
                return level > maxlevel ? maxlevel : level;
            } catch (Exception e) {
            }
        }
        return 1;
    }

    /**
     * 屏幕的触摸事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();
        int x = (int) event.getX();// 获得x轴坐标
        int y = (int) event.getY();// 获得y轴坐标

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                changeState(STATE_RECORDING);
                break;
            case MotionEvent.ACTION_MOVE:

                if (isRecording) {
                    // 如果想要取消，根据x,y的坐标看是否需要取消
                    if (wantToCancle(x, y)) {
                        changeState(STATE_WANT_TO_CANCEL);
                    } else {
                        changeState(STATE_RECORDING);
                    }
                }

                break;
            case MotionEvent.ACTION_UP:
                if (!mReady) {
                    reset();
                    return super.onTouchEvent(event);
                }
                if (!isRecording || mTime < 0.6f) {
                    mDialogManager.tooShort();
                    recorder.completeRecord(true);
                    mHandler.sendEmptyMessageDelayed(MSG_DIALOG_DIMISS, 1000);// 延迟显示对话框
                } else if (mCurrentState == STATE_RECORDING) { // 正在录音的时候，结束
                    mDialogManager.dimissDialog();
                    recorder.completeRecord(false);

                } else if (mCurrentState == STATE_WANT_TO_CANCEL) { // 想要取消
                    mDialogManager.dimissDialog();
                    recorder.completeRecord(true);
                }
                reset();
                break;

        }
        return super.onTouchEvent(event);
    }

    /**
     * 恢复状态及标志位
     */
    private void reset() {
        isRecording = false;
        mTime = 0;
        mReady = false;
        changeState(STATE_NORMAL);
    }

    private boolean wantToCancle(int x, int y) {
        if (x < 0 || x > getWidth()) { // 超过按钮的宽度
            return true;
        }
        // 超过按钮的高度
        if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
            return true;
        }

        return false;
    }

    /**
     * 改变
     */
    private void changeState(int state) {
        if (mCurrentState != state) {
            mCurrentState = state;
            switch (state) {
                case STATE_NORMAL:
                    setBackgroundResource(R.drawable.btn_recorder_normal);
                    setText(R.string.str_recorder_normal);
                    break;

                case STATE_RECORDING:
                    setBackgroundResource(R.drawable.btn_recorder_recording);
                    setText(R.string.str_recorder_recording);
                    if (isRecording) {
                        mDialogManager.recording();
                    }
                    break;

                case STATE_WANT_TO_CANCEL:
                    setBackgroundResource(R.drawable.btn_recorder_recording);
                    setText(R.string.str_recorder_want_cancel);
                    mDialogManager.wantToCancel();
                    break;
            }
        }
    }


}
